package com.bf.electroplating.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bf.electroplating.login.UserContext;
import com.bf.electroplating.login.UserDetail;
import com.bf.electroplating.mapper.SewagePlantManualDetectionMapper;
import com.bf.electroplating.pojo.entity.ComCompany;
import com.bf.electroplating.pojo.entity.SewagePlantManualDetection;
import com.bf.electroplating.pojo.vo.sewagePlantManualDetection.*;
import com.bf.electroplating.service.ISewagePlantManualDetectionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 污水厂预排口手工检测数据表 服务实现类
 * </p>
 *
 * @author gzd
 * @since 2025-09-11
 */
@Slf4j
@Service
public class SewagePlantManualDetectionServiceImpl extends ServiceImpl<SewagePlantManualDetectionMapper, SewagePlantManualDetection> implements ISewagePlantManualDetectionService {

    @Override
    public String importSewagePlantManualDetectionData(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return "请选择要导入的文件";
        }
        
        // 检查文件类型
        String fileName = file.getOriginalFilename();
        if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
            return "请上传Excel文件(.xlsx或.xls格式)";
        }
        
        try {
            log.info("开始导入污水厂预排口手工检测数据文件: {}", fileName);
            
            // 使用POI读取Excel文件
            List<SewagePlantManualDetection> dataList = parseExcelFile(file);
            
            if (dataList.isEmpty()) {
                return "文件中没有有效数据";
            }
            
            // 批量保存数据
            this.saveBatch(dataList);
            
            log.info("污水厂预排口手工检测数据导入完成: {}, 共导入{}条数据", fileName, dataList.size());
            return "污水厂预排口手工检测数据导入成功，共导入" + dataList.size() + "条数据";
            
        } catch (IOException e) {
            log.error("污水厂预排口手工检测数据导入失败: {}", e.getMessage(), e);
            return "文件读取失败: " + e.getMessage();
        } catch (Exception e) {
            log.error("污水厂预排口手工检测数据导入异常: {}", e.getMessage(), e);
            return "导入失败: " + e.getMessage();
        }
    }
    
    /**
     * 解析Excel文件
     * 每个Sheet表示一个月的数据，格式：第1行是日期，第2行是类型，第3-5行是数据，然后重复
     */
    private List<SewagePlantManualDetection> parseExcelFile(MultipartFile file) throws IOException {
        List<SewagePlantManualDetection> resultList = new ArrayList<>();
        
        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            int numberOfSheets = workbook.getNumberOfSheets();
            log.info("Excel文件包含{}个Sheet", numberOfSheets);
            
            for (int sheetIndex = 0; sheetIndex < numberOfSheets; sheetIndex++) {
                Sheet sheet = workbook.getSheetAt(sheetIndex);
                String sheetName = sheet.getSheetName();
                log.info("处理Sheet: {}", sheetName);
                
                List<SewagePlantManualDetection> sheetData = parseSheet(sheet, sheetName);
                resultList.addAll(sheetData);
                
                log.info("Sheet {} 处理完成，共{}条数据", sheetName, sheetData.size());
            }
        }
        
        return resultList;
    }
    
    /**
     * 解析单个Sheet
     */
    private List<SewagePlantManualDetection> parseSheet(Sheet sheet, String sheetName) {
        List<SewagePlantManualDetection> resultList = new ArrayList<>();
        
        int lastRowNum = sheet.getLastRowNum();
        log.info("Sheet {} 共有{}行数据", sheetName, lastRowNum + 1);
        
        List<String> currentDates = null;
        String currentType = null;
        
        for (int rowIndex = 0; rowIndex <= lastRowNum; rowIndex++) {
            Row row = sheet.getRow(rowIndex);
            if (row == null) {
                continue;
            }
            
            int rowNumber = rowIndex + 1;
            
            // 第1行：日期行
            if (rowNumber % 5 == 1) {
                currentDates = extractDatesFromRow(row, sheetName);
                log.info("第{}行 - 提取到{}个日期: {}", rowNumber, currentDates.size(), currentDates);
            }
            // 第2行：类型行
            else if (rowNumber % 5 == 2) {
                currentType = extractTypeFromRow(row);
                log.info("第{}行 - 类型: {}", rowNumber, currentType);
            }
            // 第3-5行：数据行
            else if (rowNumber % 5 >= 3 && rowNumber % 5 <= 5||rowNumber % 5 ==0) {
                if (currentDates != null && !currentDates.isEmpty() && currentType != null) {
                    List<SewagePlantManualDetection> dataForThisRow = parseDataRow(row, currentDates, currentType, rowNumber, sheetName);
                    resultList.addAll(dataForThisRow);
                }
            }
        }
        
        return resultList;
    }
    
    /**
     * 从日期行提取所有日期信息
     * 格式：1列空格，2列日期，3、4列空格，5列日期，6、7列空格，8列日期，9、10列空格，11列日期，12、13列空格，14列日期，15、16列空格
     */
    private List<String> extractDatesFromRow(Row row, String sheetName) {
        List<String> dates = new ArrayList<>();
        
        for (int cellIndex = 0; cellIndex < row.getLastCellNum(); cellIndex++) {
            Cell cell = row.getCell(cellIndex);
            if (cell != null) {
                String cellValue = getCellValueAsString(cell);
                if (cellValue != null && !cellValue.isEmpty()) {
                    String formattedDate = null;
                    
                    // 处理日期格式：Mon Mar 10 00:00:00 CST 2025
                    if (cellValue.contains("CST") || cellValue.contains("GMT")) {
                        formattedDate = formatDateStringFromCST(cellValue);
                    }
                    // 处理中文日期格式：3月8日
                    else if (cellValue.contains("月") && cellValue.contains("日")) {
                        formattedDate = formatDateString(cellValue, sheetName);
                    }
                    
                    if (formattedDate != null) {
                        dates.add(formattedDate);
                        log.info("提取到日期: {} -> {}", cellValue, formattedDate);
                    }
                }
            }
        }
        
        return dates;
    }
    
    /**
     * 从类型行提取类型信息
     */
    private String extractTypeFromRow(Row row) {
        for (int cellIndex = 0; cellIndex < row.getLastCellNum(); cellIndex++) {
            Cell cell = row.getCell(cellIndex);
            if (cell != null) {
                String cellValue = getCellValueAsString(cell);
                if (cellValue != null && !cellValue.isEmpty() && cellValue.contains("（mg/l）")) {
                    return "mg/l";
                }
            }
        }
        return null;
    }
    
    /**
     * 解析数据行
     * 根据日期列表和检测数据创建多条记录
     */
    private List<SewagePlantManualDetection> parseDataRow(Row row, List<String> dates, String type, int rowNumber, String sheetName) {
        List<SewagePlantManualDetection> resultList = new ArrayList<>();
        
        if (row.getLastCellNum() < 2) {
            return resultList;
        }
        
        Cell firstCell = row.getCell(0);
        if (firstCell == null) {
            return resultList;
        }
        
        String outletType = getCellValueAsString(firstCell);
        if (outletType == null || outletType.trim().isEmpty()) {
            return resultList;
        }
        
        // 根据日期数量确定每组数据的列数
        // 每组数据包含：1列日期 + 2列空格 + 3列检测数据（六价铬、总镍、总铬）
        int columnsPerDate = 3; // 1列日期 + 2列空格 + 3列检测数据
        
        // 为每个日期创建记录
        for (int dateIndex = 0; dateIndex < dates.size(); dateIndex++) {
            String date = dates.get(dateIndex);
            
            // 计算该日期对应的检测数据列位置
            // 第1个日期：列1-3（跳过第0列出水口类型）
            // 第2个日期：列7-9
            // 第3个日期：列13-15
            // 第4个日期：列19-21
            // 第5个日期：列25-27
            int dataStartColumn = 1 + dateIndex * columnsPerDate;
            
            if (dataStartColumn + 2 < row.getLastCellNum()) {
                BigDecimal chromium6 = parseDecimalFromCell(row.getCell(dataStartColumn));
                BigDecimal nickelTotal = parseDecimalFromCell(row.getCell(dataStartColumn + 1));
                BigDecimal chromiumTotal = parseDecimalFromCell(row.getCell(dataStartColumn + 2));
                
                // 至少有一个检测因子不为空才创建记录
                if (chromium6 != null || nickelTotal != null || chromiumTotal != null) {
                    SewagePlantManualDetection entity = new SewagePlantManualDetection();
                    
                    entity.setId(UUID.randomUUID().toString().replace("-", ""));
                    entity.setPlantName("武义县碧水环保科技有限公司");
                    entity.setPlantCode("9133072333696820XL");
                    entity.setDetectionDate(LocalDate.parse(date));
                    entity.setOutletType(outletType.trim());
                    entity.setChromium6(chromium6);
                    entity.setNickelTotal(nickelTotal);
                    entity.setChromiumTotal(chromiumTotal);
                    entity.setInputBy("系统导入");
                    entity.setInputDate(LocalDateTime.now());
                    entity.setCreateBy("系统导入");
                    entity.setCreateTime(LocalDateTime.now());
                    entity.setUpdateBy("系统导入");
                    entity.setUpdateTime(LocalDateTime.now());
                    entity.setDelFlag("0");
                    
                    resultList.add(entity);
                    
                    log.info("创建记录: Sheet={}, 日期={}, 出水口类型={}, 六价铬={}, 总镍={}, 总铬={}", 
                        sheetName, date, outletType, chromium6, nickelTotal, chromiumTotal);
                }
            }
        }
        
        return resultList;
    }
    
    /**
     * 获取单元格值作为字符串
     */
    private String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return null;
        }
        
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return null;
        }
    }
    
    /**
     * 从单元格解析数字
     */
    private BigDecimal parseDecimalFromCell(Cell cell) {
        if (cell == null) {
            return null;
        }
        
        try {
            switch (cell.getCellType()) {
                case NUMERIC:
                    return BigDecimal.valueOf(cell.getNumericCellValue());
                case STRING:
                    String stringValue = cell.getStringCellValue().trim();
                    if (stringValue.isEmpty()) {
                        return null;
                    }
                    return new BigDecimal(stringValue);
                default:
                    return null;
            }
        } catch (NumberFormatException e) {
            log.warn("数字格式解析失败: {}", getCellValueAsString(cell));
            return null;
        }
    }
    
    /**
     * 格式化日期字符串
     */
    private String formatDateString(String dateStr, String sheetName) {
        try {
            // 处理"3月8日"格式
            if (dateStr.contains("月") && dateStr.contains("日")) {
                String monthDay = dateStr.replace("月", "-").replace("日", "");
                String[] parts = monthDay.split("-");
                if (parts.length == 2) {
                    int month = Integer.parseInt(parts[0]);
                    int day = Integer.parseInt(parts[1]);
                    
                    // 从Sheet名称推断年份，如果Sheet名称包含年份信息
                    int year = extractYearFromSheetName(sheetName);
                    return String.format("%d-%02d-%02d", year, month, day);
                }
            }
        } catch (Exception e) {
            log.warn("日期格式解析失败: {}", dateStr);
        }
        return null;
    }
    
    /**
     * 从Sheet名称提取年份
     */
    private int extractYearFromSheetName(String sheetName) {
        try {
            // 尝试从Sheet名称中提取年份，如"2024年3月"或"3月"
            if (sheetName.contains("年")) {
                String[] parts = sheetName.split("年");
                if (parts.length > 0) {
                    return Integer.parseInt(parts[0]);
                }
            }
        } catch (Exception e) {
            log.warn("从Sheet名称提取年份失败: {}", sheetName);
        }
        
        // 默认返回2024年
        return 2024;
    }
    
    /**
     * 格式化CST格式的日期字符串
     * 处理格式：Mon Mar 10 00:00:00 CST 2025
     */
    private String formatDateStringFromCST(String dateStr) {
        try {
            // 处理格式：Mon Mar 10 00:00:00 CST 2025
            if (dateStr.contains("CST") || dateStr.contains("GMT")) {
                // 提取月份和日期
                String[] parts = dateStr.split("\\s+");
                if (parts.length >= 4) {
                    String monthStr = parts[1]; // Mar
                    String dayStr = parts[2];   // 10
                    String yearStr = parts[parts.length - 1]; // 2025
                    
                    // 转换月份名称
                    int month = convertMonthNameToNumber(monthStr);
                    int day = Integer.parseInt(dayStr);
                    int year = Integer.parseInt(yearStr);
                    
                    return String.format("%d-%02d-%02d", year, month, day);
                }
            }
        } catch (Exception e) {
            log.warn("CST日期格式解析失败: {}", dateStr);
        }
        return null;
    }
    
    /**
     * 将月份名称转换为数字
     */
    private int convertMonthNameToNumber(String monthName) {
        switch (monthName.toLowerCase()) {
            case "jan": return 1;
            case "feb": return 2;
            case "mar": return 3;
            case "apr": return 4;
            case "may": return 5;
            case "jun": return 6;
            case "jul": return 7;
            case "aug": return 8;
            case "sep": return 9;
            case "oct": return 10;
            case "nov": return 11;
            case "dec": return 12;
            default: 
                log.warn("未知的月份名称: {}", monthName);
                return 1;
        }
    }

    @Override
    public SewagePlantManualDetectionPageVO pageList(SewagePlantManualDetectionQueryDTO queryDTO) {
        log.info("开始分页查询污水厂预排口手工检测数据，查询条件：{}", queryDTO);
        
        // 构建查询条件
        LambdaQueryWrapper<SewagePlantManualDetection> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(queryDTO.getPlantName())) {
            queryWrapper.like(SewagePlantManualDetection::getPlantName, queryDTO.getPlantName());
        }
        
        if (StringUtils.hasText(queryDTO.getPlantCode())) {
            queryWrapper.eq(SewagePlantManualDetection::getPlantCode, queryDTO.getPlantCode());
        }
        
        if (StringUtils.hasText(queryDTO.getOutletType())) {
            queryWrapper.eq(SewagePlantManualDetection::getOutletType, queryDTO.getOutletType());
        }
        
        if (queryDTO.getStartDate() != null) {
            LocalDate start=LocalDate.parse(queryDTO.getStartDate()+"-01");
            LocalDate end=LocalDate.parse(queryDTO.getStartDate()+"-01").plusMonths(1).minusDays(1);
            queryWrapper.between(SewagePlantManualDetection::getDetectionDate, start,end);
        }

        
        if (StringUtils.hasText(queryDTO.getInputBy())) {
            queryWrapper.like(SewagePlantManualDetection::getInputBy, queryDTO.getInputBy());
        }
        
        // 只查询未删除的数据
        queryWrapper.eq(SewagePlantManualDetection::getDelFlag, "0");
        
        // 按检测日期倒序排列
        queryWrapper.orderByDesc(SewagePlantManualDetection::getDetectionDate);
        
        // 分页查询
        List<SewagePlantManualDetection> result = this.list(queryWrapper);
        
        // 转换为VO

        List<SewagePlantManualDetectionVO> voList = new ArrayList<>();
        for (SewagePlantManualDetection entity : result) {
            SewagePlantManualDetectionVO vo = new SewagePlantManualDetectionVO();
            BeanUtils.copyProperties(entity, vo);
            voList.add(vo);
        }

        SewagePlantManualDetectionPageVO sewagePlantManualDetectionPageVO=new SewagePlantManualDetectionPageVO();
        Map<String,List<SewagePlantManualDetectionVO>> map = voList.stream().collect(Collectors.groupingBy(j->j.getDetectionDate().format(DateTimeFormatter.ISO_DATE)));
        List<SewagePlantManualDetectionPageDayVO> sewagePlantManualDetectionPageDayVOS=new ArrayList<>();
        for (String key : map.keySet()) {
            SewagePlantManualDetectionPageDayVO sewagePlantManualDetectionPageDayVO=new SewagePlantManualDetectionPageDayVO();
            sewagePlantManualDetectionPageDayVO.setDay(key);
            sewagePlantManualDetectionPageDayVO.setSewagePlantManualDetection(map.get(key).stream()
                    .sorted(Comparator.comparing(SewagePlantManualDetectionVO::getSort)).toList());
            sewagePlantManualDetectionPageDayVO.setInputBy(map.get(key).get(0).getInputBy());
            sewagePlantManualDetectionPageDayVO.setPlantName(map.get(key).get(0).getPlantName());
            sewagePlantManualDetectionPageDayVO.setStatus(checkStatus(map.get(key)));
            sewagePlantManualDetectionPageDayVOS.add(sewagePlantManualDetectionPageDayVO);
        }
        sewagePlantManualDetectionPageDayVOS=sewagePlantManualDetectionPageDayVOS.stream().sorted(Comparator.comparing(SewagePlantManualDetectionPageDayVO::getDay)).toList();
        sewagePlantManualDetectionPageVO.setSewagePlantManualDetectionPageDayVOList(sewagePlantManualDetectionPageDayVOS);
        log.info("分页查询完成，共{}条数据", voList.size());
        return sewagePlantManualDetectionPageVO;
    }

    private String checkStatus(List<SewagePlantManualDetectionVO> sewagePlantManualDetectionVOS) {
        String result="0";
        for (SewagePlantManualDetectionVO entity : sewagePlantManualDetectionVOS) {
           if (entity.getChromiumTotal()!=null){
               return "1";
           }
            if (entity.getChromium6()!=null){
                return "1";
            }
            if (entity.getNickelTotal()!=null){
                return "1";
            }
        }
        return result;
    }
    @Override
    public SewagePlantManualDetectionVO getDetail(String id) {
        log.info("开始获取污水厂预排口手工检测数据详情，ID：{}", id);
        
        SewagePlantManualDetection entity = this.getById(id);
        if (entity == null) {
            throw new RuntimeException("数据不存在");
        }
        
        SewagePlantManualDetectionVO vo = new SewagePlantManualDetectionVO();
        BeanUtils.copyProperties(entity, vo);
        
        log.info("获取详情成功");
        return vo;
    }

    @Override
    public Boolean updateDetectionData(SewagePlantManualDetectionUpdateListDTO sewagePlantManualDetectionUpdateListDTO) {
        for (SewagePlantManualDetectionUpdateDTO updateDTO:sewagePlantManualDetectionUpdateListDTO.getSewagePlantManualDetection()) {
            log.info("开始更新污水厂预排口手工检测数据，ID：{}", updateDTO.getId());

            // 检查数据是否存在
            SewagePlantManualDetection existingEntity = this.getById(updateDTO.getId());
            if (existingEntity == null) {
                throw new RuntimeException("数据不存在");
            }

            // 更新数据
            SewagePlantManualDetection entity = new SewagePlantManualDetection();
            BeanUtils.copyProperties(updateDTO, entity);
            entity.setUpdateTime(LocalDateTime.now());
            entity.setInputBy(UserContext.getUser().getUserName());
            UpdateWrapper<SewagePlantManualDetection> updateWrapper=new UpdateWrapper<SewagePlantManualDetection>();
            updateWrapper.eq("id",updateDTO.getId());
            updateWrapper.set("CHROMIUM_6",updateDTO.getChromium6());
            updateWrapper.set("CHROMIUM_TOTAL",updateDTO.getChromiumTotal());
            updateWrapper.set("NICKEL_TOTAL",updateDTO.getNickelTotal());
            updateWrapper.set("INPUT_BY",UserContext.getUser().getUserName());
            updateWrapper.set("INPUT_DATE",LocalDateTime.now());
            boolean result = this.update(updateWrapper);
            log.info("更新结果：{}", result);
        }
        return true;
    }

    @Override
    public Boolean deleteDetectionData(String id) {
        log.info("开始删除污水厂预排口手工检测数据，ID：{}", id);
        
        // 检查数据是否存在
        SewagePlantManualDetection entity = this.getById(id);
        if (entity == null) {
            throw new RuntimeException("数据不存在");
        }
        
        // 逻辑删除
        entity.setDelFlag("1");
        entity.setUpdateTime(LocalDateTime.now());
        entity.setUpdateBy("系统删除");
        
        boolean result = this.updateById(entity);
        
        log.info("删除结果：{}", result);
        return result;
    }

    @Override
    public void exportData(SewagePlantManualDetectionQueryDTO queryDTO, HttpServletResponse response) throws IOException {
        log.info("开始导出污水厂预排口手工检测数据，查询条件：{}", queryDTO);
        
        // 构建查询条件（与分页查询相同）
        LambdaQueryWrapper<SewagePlantManualDetection> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(queryDTO.getPlantName())) {
            queryWrapper.like(SewagePlantManualDetection::getPlantName, queryDTO.getPlantName());
        }
        
        if (StringUtils.hasText(queryDTO.getPlantCode())) {
            queryWrapper.eq(SewagePlantManualDetection::getPlantCode, queryDTO.getPlantCode());
        }
        
        if (StringUtils.hasText(queryDTO.getOutletType())) {
            queryWrapper.eq(SewagePlantManualDetection::getOutletType, queryDTO.getOutletType());
        }



        if (queryDTO.getStartDate() != null) {
            LocalDate start=LocalDate.parse(queryDTO.getStartDate()+"-01");
            LocalDate end=LocalDate.parse(queryDTO.getStartDate()+"-01").plusMonths(1).minusDays(1);
            queryWrapper.between(SewagePlantManualDetection::getDetectionDate, start,end);
        }

        if (StringUtils.hasText(queryDTO.getInputBy())) {
            queryWrapper.like(SewagePlantManualDetection::getInputBy, queryDTO.getInputBy());
        }
        
        // 只查询未删除的数据
        queryWrapper.eq(SewagePlantManualDetection::getDelFlag, "0");
        
        // 按检测日期倒序排列
        queryWrapper.orderByDesc(SewagePlantManualDetection::getDetectionDate);
        
        // 查询所有数据
        List<SewagePlantManualDetection> dataList = this.list(queryWrapper);
        
        // 转换为VO
        List<SewagePlantManualDetectionVO> voList = new ArrayList<>();
        for (SewagePlantManualDetection entity : dataList) {
            SewagePlantManualDetectionVO vo = new SewagePlantManualDetectionVO();
            BeanUtils.copyProperties(entity, vo);
            voList.add(vo);
        }
        
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + 
            java.net.URLEncoder.encode("污水厂预排口手工检测数据", "UTF-8") + ".xlsx");
        
        // 使用EasyExcel导出
        EasyExcel.write(response.getOutputStream(), SewagePlantManualDetectionVO.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .sheet("污水厂预排口手工检测数据")
                .doWrite(voList);
        
        log.info("导出完成，共{}条数据", voList.size());
    }

    @Override
    public Boolean generateDailyBlankData() {
        log.info("开始生成当月空白检测数据");
        
        try {
            LocalDate today = LocalDate.now();
            LocalDateTime now = LocalDateTime.now();
            
            // 获取当月第一天和最后一天
            LocalDate firstDayOfMonth = today.withDayOfMonth(1).minusMonths(3);
            LocalDate lastDayOfMonth = today.withDayOfMonth(today.lengthOfMonth());
            
            log.info("准备为{}年{}月生成数据，日期范围：{} 至 {}", 
                    today.getYear(), today.getMonthValue(), firstDayOfMonth, lastDayOfMonth);
            // 查询当月已存在数据的日期
            LambdaQueryWrapper<SewagePlantManualDetection> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.ge(SewagePlantManualDetection::getDetectionDate, firstDayOfMonth);
            queryWrapper.le(SewagePlantManualDetection::getDetectionDate, lastDayOfMonth);
            queryWrapper.eq(SewagePlantManualDetection::getDelFlag, "0");
            queryWrapper.eq(SewagePlantManualDetection::getPlantName,"武义县新禹水处理有限公司");
            queryWrapper.select(SewagePlantManualDetection::getDetectionDate);
            
            List<SewagePlantManualDetection> existingData = this.list(queryWrapper);
            Set<LocalDate> existingDates = existingData.stream()
                    .map(SewagePlantManualDetection::getDetectionDate)
                    .collect(Collectors.toSet());
            
            log.info("当月已存在{}天的数据", existingDates.size());
            
            List<SewagePlantManualDetection> blankDataList = new ArrayList<>();
            int skippedDays = 0;
            int generatedDays = 0;
            
            // 遍历当月每一天
            LocalDate currentDate = firstDayOfMonth;
            while (!currentDate.isAfter(lastDayOfMonth)) {
                // 检查当天是否已有数据
                if (existingDates.contains(currentDate)) {
                    log.debug("日期 {} 已存在数据，跳过生成", currentDate);
                    skippedDays++;
                } else {
                    log.debug("为日期 {} 生成空白数据", currentDate);


                    // 武义县新禹水处理有限公司的3个污水类型
                    String[] xinyuOutletTypes = {"含铬废水", "含镍废水", "前处理废水", "氰铜废水", "酸碱废水", "其他废水"};
                    for (int i=1;i<=xinyuOutletTypes.length;i++ ) {
                        String outletType=xinyuOutletTypes[i-1];
                        SewagePlantManualDetection blankData = createBlankDetectionData(
                            "武义县新禹水处理有限公司",
                            "913307230753494931",
                            outletType,
                            currentDate,
                            now,
                            i
                        );
                        blankDataList.add(blankData);
                    }
                    // 武义县碧水环保科技有限公司的3个污水类型
                    generatedDays++;
                }
                
                currentDate = currentDate.plusDays(1);
            }
             today = LocalDate.now();
             now = LocalDateTime.now();

            // 获取当月第一天和最后一天
             firstDayOfMonth = today.withDayOfMonth(1).minusMonths(3);
             lastDayOfMonth = today.withDayOfMonth(today.lengthOfMonth());
             queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.ge(SewagePlantManualDetection::getDetectionDate, firstDayOfMonth);
            queryWrapper.le(SewagePlantManualDetection::getDetectionDate, lastDayOfMonth);
            queryWrapper.eq(SewagePlantManualDetection::getDelFlag, "0");
            queryWrapper.eq(SewagePlantManualDetection::getPlantName,"武义县碧水环保科技有限公司");
            queryWrapper.select(SewagePlantManualDetection::getDetectionDate);

          existingData = this.list(queryWrapper);
          existingDates = existingData.stream()
                    .map(SewagePlantManualDetection::getDetectionDate)
                    .collect(Collectors.toSet());

            log.info("当月已存在{}天的数据", existingDates.size());

             skippedDays = 0;
             generatedDays = 0;

            // 遍历当月每一天
             currentDate = firstDayOfMonth;
            while (!currentDate.isAfter(lastDayOfMonth)) {
                // 检查当天是否已有数据
                if (existingDates.contains(currentDate)) {
                    log.debug("日期 {} 已存在数据，跳过生成", currentDate);
                    skippedDays++;
                } else {
                    log.debug("为日期 {} 生成空白数据", currentDate);

                    // 武义县碧水环保科技有限公司的3个污水类型
                    String[] bishuiOutletTypes = {"含铬废水", "含镍废水", "综合废水"};
                    for (int i=1;i<= bishuiOutletTypes.length;i++) {
                        String outletType=bishuiOutletTypes[i-1];
                        SewagePlantManualDetection blankData = createBlankDetectionData(
                                "武义县碧水环保科技有限公司",
                                "9133072333696820XL",
                                outletType,
                                currentDate,
                                now,
                                i
                        );
                        blankDataList.add(blankData);
                    }

                    generatedDays++;
                }

                currentDate = currentDate.plusDays(1);
            }
            // 批量保存
            if (!blankDataList.isEmpty()) {
                boolean result = this.saveBatch(blankDataList);
                log.info("当月空白检测数据生成完成，共为{}天生成{}条数据，跳过{}天，保存结果：{}", 
                        generatedDays, blankDataList.size(), skippedDays, result);
                return result;
            } else {
                log.info("当月所有日期均已存在数据，无需生成新数据");
                return true;
            }
            
        } catch (Exception e) {
            log.error("生成当月空白检测数据失败", e);
            return false;
        }
    }

    @Override
    public Page<SewagePlantManualDetectionVO> pageListForCompany(SewagePlantManualDetectionQueryCompanyDTO queryDTO) {
        log.info("开始分页查询污水厂预排口手工检测数据，查询条件：{}", queryDTO);

        // 构建查询条件
        LambdaQueryWrapper<SewagePlantManualDetection> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(queryDTO.getPlantName())) {
            queryWrapper.like(SewagePlantManualDetection::getPlantName, queryDTO.getPlantName());
        }

        if (StringUtils.hasText(queryDTO.getPlantCode())) {
            queryWrapper.eq(SewagePlantManualDetection::getPlantCode, queryDTO.getPlantCode());
        }

        if (StringUtils.hasText(queryDTO.getOutletType())) {
            queryWrapper.eq(SewagePlantManualDetection::getOutletType, queryDTO.getOutletType());
        }

        if (!CollectionUtils.isEmpty(queryDTO.getStartDate())&&queryDTO.getStartDate().size()>1) {
            LocalDate start=LocalDate.parse(queryDTO.getStartDate().get(0));
            LocalDate end=LocalDate.parse(queryDTO.getStartDate().get(1));
            queryWrapper.between(SewagePlantManualDetection::getDetectionDate, start,end);
        }


        if (StringUtils.hasText(queryDTO.getInputBy())) {
            queryWrapper.like(SewagePlantManualDetection::getInputBy, queryDTO.getInputBy());
        }
        queryWrapper.and(w -> w
                .isNotNull(SewagePlantManualDetection::getChromium6)
                .or()
                .isNotNull(SewagePlantManualDetection::getNickelTotal)
                .or()
                .isNotNull(SewagePlantManualDetection::getChromiumTotal)
        );
        UserDetail userDetail=UserContext.getUser();
        if (com.github.xiaoymin.knife4j.core.util.CollectionUtils.isEmpty(userDetail.getParkFunctionIds())&&userDetail.getBelongSewageCode()!=null) {
            queryWrapper.eq(SewagePlantManualDetection::getPlantCode, UserContext.getUser().getBelongSewageCode());
        }
        // 只查询未删除的数据
        queryWrapper.eq(SewagePlantManualDetection::getDelFlag, "0");
        // 按检测日期倒序排列
        queryWrapper.orderByDesc(SewagePlantManualDetection::getDetectionDate);
        Page<SewagePlantManualDetection> sewagePlantManualDetectionPage=new Page<>(queryDTO.getPageNum(),queryDTO.getPageSize());
        // 分页查询
        Page<SewagePlantManualDetection> result = this.page(sewagePlantManualDetectionPage,queryWrapper);
        Page<SewagePlantManualDetectionVO> sewagePlantManualDetectionVOPage=new Page<>();
        sewagePlantManualDetectionVOPage.setTotal(result.getTotal());
        sewagePlantManualDetectionVOPage.setRecords(result.getRecords()
                .stream().map(i->{
                    SewagePlantManualDetectionVO sewagePlantManualDetectionVO=new SewagePlantManualDetectionVO();
                    BeanUtils.copyProperties(i, sewagePlantManualDetectionVO);
                    sewagePlantManualDetectionVO.setInputDate(i.getInputDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
                    return sewagePlantManualDetectionVO;
                }).toList());
        return sewagePlantManualDetectionVOPage;
    }



    /**
     * 创建空白检测数据
     */
    private SewagePlantManualDetection createBlankDetectionData(String plantName, String plantCode,
                                                                String outletType, LocalDate detectionDate,
                                                                LocalDateTime now, int sort) {
        SewagePlantManualDetection blankData = new SewagePlantManualDetection();
        
        blankData.setId(UUID.randomUUID().toString().replace("-", ""));
        blankData.setPlantName(plantName);
        blankData.setPlantCode(plantCode);
        blankData.setDetectionDate(detectionDate);
        blankData.setOutletType(outletType);
        // 检测因子为空（null），供用户录入
        blankData.setChromium6(null);
        blankData.setNickelTotal(null);
        blankData.setChromiumTotal(null);
        blankData.setInputBy("");
        blankData.setInputDate(now);
        blankData.setCreateBy("");
        blankData.setCreateTime(now);
        blankData.setUpdateBy("");
        blankData.setUpdateTime(now);
        blankData.setParkId("1001");
        blankData.setDelFlag("0");
        blankData.setSort(sort);
        return blankData;
    }
}
